package com.rub.android.service

import com.rub.android.widget.RetrofitServiceApi
import com.rub.android.dao.TagsDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.withContext

class TagsService private constructor(
    private val tagsDao: TagsDao,
    private val serviceApi: RetrofitServiceApi
) {


    suspend fun refreshTagLists() = getTagLists()

    private suspend fun getTagLists() = withContext(Dispatchers.IO) {
        coroutineScope {
            val response = async { serviceApi.listTagsAPI() }
            var tags = response.await()

            //本地数据
            tagsDao.save(tags)
            tags
        }
    }


    companion object {
        private val TAG = javaClass.simpleName

        private var repository: TagsService? = null

        fun getInstance(dao: TagsDao, api: RetrofitServiceApi): TagsService {
            if (repository == null) {
                synchronized(TagsService::class.java) {
                    if (repository == null) {
                        repository = TagsService(dao, api)
                    }
                }
            }
            return repository!!
        }
    }
}